package com.jb.repair.util;

import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.jb.repair.common.AppConfig;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by gaobin on 2015/11/8.
 */
public class DownFileTask extends AsyncTask<String, String, Boolean> {
    private final static String TAG = "DownFileTask";

    @Override
    protected Boolean doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            Log.i(TAG, "url = " + url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();
            int fileOfLength = conn.getContentLength();
            Log.i(TAG, "fileOfLength=" + fileOfLength);
            int totallength = 0;
            int length = 0;
            InputStream in = conn.getInputStream();
            String path = params[1];
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(new File(path + params[2]));
            byte[] buff = new byte[1024 * 1024];
            while ((length = in.read(buff)) > 0) {
                out.write(buff, 0, length);
            }
            in.close();
            out.flush();
            out.close();
            Log.i(TAG, "成功");
            publishProgress();
            return true;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

}